package com.heima.wemedia.service.impl;

import com.heima.article.IArticleClient;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.wemedia.dtos.CommentConfigDto;
import com.heima.model.wemedia.dtos.CommentLikeDto;
import com.heima.model.wemedia.dtos.CommentManageDto;
import com.heima.model.wemedia.dtos.PageCommentDto;
import com.heima.model.wemedia.pojos.*;
import com.heima.model.wemedia.vos.CommentRepayListVo;
import com.heima.model.wemedia.vos.CommentVO;
import com.heima.user.IUserClient;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmCommentService;
import org.bson.types.ObjectId;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class WmCommentServiceImpl implements WmCommentService {
    @Autowired
    private IArticleClient iArticleClient;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private WmUserMapper wmUserMapper;
    @Autowired
    private IUserClient userClient;
    /**
     * 查看评论列表
     *
     * @param dto
     * @return {@link ResponseResult}
     */
    @Override
    public ResponseResult findNewsComments(PageCommentDto dto) {
        //校验参数
        if (Objects.isNull(dto)) {
            return PageResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        WmUser user = WmThreadLocalUtil.getUser();
        dto.setWmUserId(user.getId());
        return iArticleClient.findNewsComments(dto);
    }

    /**
     * 打开或关闭评论
     *
     * @param dto
     * @return {@link ResponseResult}
     */
    @Override
    public ResponseResult updateCommentStatus(CommentConfigDto dto) {
        //参数校验
        if (dto == null || dto.getArticleId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmUser wmUser = WmThreadLocalUtil.getUser();
        //app端用户id
        WmUser dbUser = wmUserMapper.selectById(wmUser.getId());
        Integer apUserId = dbUser.getApUserId();
        //清除文章的所有评论
        List<ApComment> apCommentList = mongoTemplate.find(Query.query(Criteria
                .where("entryId")
                .is(dto.getArticleId())
                .and("authorId")
                .is(apUserId)), ApComment.class);
        for (ApComment apComment : apCommentList) {
            List<ApCommentRepay> commentRepayList = mongoTemplate.find(Query.query(Criteria
                    .where("commentId")
                    .is(apComment.getId())
                    .and("authorId")
                    .is(apUserId)), ApCommentRepay.class);
            List<String> commentRepayIdList = commentRepayList.stream().map(ApCommentRepay::getId)
                    .distinct().collect(Collectors.toList());
            //删除所有的评论回复点赞数据
            mongoTemplate.remove(Query.query(Criteria
                    .where("commentRepayId")
                    .in(commentRepayIdList)
                    .and("authorId")
                    .is(apUserId)), ApCommentRepayLike.class);

            //删除该评论的所有的回复内容
            mongoTemplate.remove(Query.query(Criteria
                    .where("entryId")
                    .is(dto.getArticleId())
                    .and("authorId")
                    .is(apUserId)), ApCommentRepay.class);

            //删除评论的点赞
            mongoTemplate.remove(Query.query(Criteria
                    .where("commentId")
                    .is(apComment.getId())
                    .and("authorId")
                    .is(apUserId)), ApCommentLike.class);
        }
        //删除评论
        mongoTemplate.remove(Query.query(Criteria.where("entryId")
                .is(dto.getArticleId())
                .and("authorId")
                .is(apUserId)), ApComment.class);
        //修改文章配置状态
        return iArticleClient.updateArticleStatus(dto);
    }

    /**
     * 查看文章评论详情
     *
     * @param dto
     * @return {@link ResponseResult}
     */
    @Override
    public ResponseResult list(CommentManageDto dto) {
        if (dto == null || dto.getArticleId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        List<CommentRepayListVo> commentRepayListVoList = new ArrayList<>();

        Query query = Query.query(Criteria.where("entryId").is(dto.getArticleId()));
        Pageable pageable =  PageRequest.of(dto.getPage(),dto.getSize());
        query.with(pageable);
        query.with(Sort.by(Sort.Direction.DESC, "createdTime"));

        List<ApComment> list = mongoTemplate.find(query, ApComment.class);

        for (ApComment apComment : list) {
            CommentRepayListVo vo = new CommentRepayListVo();
            vo.setApComments(apComment);
            Query query2 = Query.query(Criteria.where("commentId").is(apComment.getId()));
            query2.with(Sort.by(Sort.Direction.DESC, "createdTime"));
            List<ApCommentRepay> apCommentRepays = mongoTemplate.find(query2, ApCommentRepay.class);
            vo.setApCommentRepays(apCommentRepays);

            commentRepayListVoList.add(vo);
        }

        return ResponseResult.okResult(commentRepayListVoList);
    }

    /**
     * 评论点赞
     * @param commentLikeDto
     * @return {@link ResponseResult}
     */
    @Override
    public ResponseResult like(CommentLikeDto commentLikeDto) {
        //1.检查参数
        if (commentLikeDto == null || commentLikeDto.getCommentId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //拿到评论对象
        ApComment apComment = mongoTemplate.findById(commentLikeDto.getCommentId(), ApComment.class);

        WmUser wmUser = WmThreadLocalUtil.getUser();
        WmUser dbUser = wmUserMapper.selectById(wmUser.getId());
        if(dbUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //获取app端用户信息
        ApUser apUser = userClient.findUserById(dbUser.getApUserId());

        //3.点赞
        if (apComment != null && commentLikeDto.getOperation() == 0) {
            //更新评论点赞数量
            apComment.setLikes(apComment.getLikes() + 1);
            mongoTemplate.save(apComment);

            //保存评论点赞数据
            ApCommentLike apCommentLike = new ApCommentLike();
            apCommentLike.setCommentId(apComment.getId());
            apCommentLike.setAuthorId(apUser.getId());
            mongoTemplate.save(apCommentLike);
        } else {
            //4.取消点赞
            //更新评论点赞数量
            int tmp = apComment.getLikes() - 1;
            tmp = tmp < 1 ? 0 : tmp;
            apComment.setLikes(tmp);
            mongoTemplate.save(apComment);

            //删除评论点赞
            Query query = Query.query(Criteria
                    .where("commentId")
                    .is(apComment.getId())
                    .and("authorId")
                    .is(apUser.getId()));
            mongoTemplate.remove(query, ApCommentLike.class);
        }
        Map<String, Object> result = new HashMap<>();
        result.put("likes", apComment.getLikes());
        return ResponseResult.okResult(result);
    }
}
